package com.atguigu.gulimall.order.web;

import com.atguigu.common.exception.NoStockException;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    /**
     * 去订单确认页
     *
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        //1、收集确认页需要的数据
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        //2、展示确认页的数据
        model.addAttribute("orderConfirmData", orderConfirmVo);
        return "confirm";
    }

    /**
     * 收集所需订单信息，生成订单
     *
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes) {
        try {
            //下单
            SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
            if (responseVo.getCode() == 0) {
                //下单成功来到支付页
                model.addAttribute("submitOrderResp", responseVo);
                return "pay";
            } else {
                //下单失败，重新回到订单确认页
                String msg = "下单失败: ";
                switch (responseVo.getCode()) {
                    case 1:
                        msg += "订单信息过去，请刷新后再试";
                        break;
                    case 2:
                        msg += "订单价格发送变化，请确认后再试";
                        break;
                    case 3:
                        msg += "库存锁定失败，库存不足";
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception ex) {
            if (ex instanceof NoStockException) {
                String msg = "下单失败，商品无库存";
                redirectAttributes.addFlashAttribute("msg", msg);
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
